package com.bs.areport.action.basic;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bs.areport.service.basic.DepartDao;
import com.bs.areport.service.util.DataUtil;
import com.bs.areport.service.util.MethodUtil;
import com.bs.restframework.context.SystemContext;
import com.bs.restframework.context.util.SystemContextUtil;
import com.bs.restframework.session.UserSession;
import com.bs.restframework.web.result.ResultModle;
import com.bs.restframework.web.result.ResultType;

/** 
 * @ClassName   类名：DepartAction 
 * @Description 功能说明：使用单位控制类
 * TODO
 ************************************************************************
 * @date        创建日期：2012-03-08
 * @author      创   建  人：陈金滨
 * @version     版   本  号：V1.0
 ***************************修订记录*************************************
 * 
 * 2012-03-08   陈金滨        创建类
 *   
 ***********************************************************************
 */

public class DepartAction {
	
	private DepartDao dao;
	
	public  DepartDao getDao() {
		return dao;
	}

	public void setDao(DepartDao dao) {
		this.dao = dao;
	}
	
	/**
	 * 
	 * <p>函数名称：list</p>
	 * <p>功能说明：查询列表</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-08</p>
	 * <p>作者：李新宇</p>
	 */
	public ResultModle list() throws Exception
	{
		Map<String, Object> params = SystemContext.getInParams();
		
        Map<String, Object> resultBean = dao.list(params);
        
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);
	}
	/**
	 * 
	 * <p>函数名称：qrylist</p>
	 * <p>功能说明：点击树查询并刷新网格</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-28</p>
	 * <p>作者：陈金滨</p>
	 */
	public ResultModle qrylist() throws Exception
	{
		Map<String, Object> params = SystemContext.getInParams();
		
        Map<String, Object> resultBean = dao.qrylist(params);
        
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);
	}
	
	/**
	 * 
	 * <p>函数名称：tree</p>
	 * <p>功能说明：获取单位树</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-13</p>
	 * <p>作者：陈金滨</p>
	 */
	public ResultModle tree() throws Exception
	{
		Map<String, Object> params = SystemContext.getInParams();
		
        List<Map> listMap = dao.tree(params);
        
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", listMap);
	}
	/**	  
	 * <p>函数名称：getUser</p>
	 * <p>功能说明：获取用户类型</p>
	 * <p>创建时间：2012-08-08</p>
	 * <p>作          者：陈金滨</p>
	 */
	public ResultModle getUser() throws Exception
	{
		Map<String, Object> params = SystemContext.getInParams();
		String token =(String)params.get("Token");
		UserSession userSession = SystemContextUtil.getSessionMange().getUserSession((String)params.get("Token"));
		String userid=userSession.getUserID().toString() ;
		String userType = userSession.getUserType().toString() ;	
		Map<String, Object> resultBean= new HashMap<String, Object>();
		
		resultBean.put("USERTYPE", userType);			
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);		
		
	}	
	/**
	 * 
	 * <p>函数名称：userTree</p>
	 * <p>功能说明：获取单位树</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-13</p>
	 * <p>作者：陈金滨</p>
	 */
	public ResultModle userTree() throws Exception
	{
		Map<String, Object> params = SystemContext.getInParams();
		Map<String, Object> deptJC = dao.getDWJC();
		String departJC = (String) deptJC.get("F_ITEM1");
		
		String token =(String)params.get("Token");
		UserSession userSession = SystemContextUtil.getSessionMange().getUserSession((String)params.get("Token"));
		String userID = userSession.getUserID().toString();
		String deptCode = "" ;
		if(userID==null||"".equals(userID))
		{
			deptCode="" ;
		}
		else
		{
			Map<String, Object> resultBean=dao.getUserInfoByID(userID);
			String deptID = (String) resultBean.get("F_DEPTID");
			if(deptID!=null&&deptID.equals("")==false)
			{
				Map<String, Object> deptMap=dao.getInfoByID(deptID);
				deptCode = (String) deptMap.get("F_CODE");
			}
		}
		Integer level = null;
		if("".equals(deptCode)==false)
		{
			level= DataUtil.getLevel(departJC, deptCode);	
		}
		else
		{
			level= 0;
		}		
		if(level!=null&&"".equals(level)!=true)
		{
			String condition = " AND (F_LEVEL="+level+" OR F_LEVEL="+(level+1)+")"	;
			params.put("Dcon",condition);	
		}		
        List<Map> listMap = dao.userTree(params);
        
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", listMap);
	}	
		
	/**
	 * 
	 * <p>函数名称：getMaxCode</p>
	 * <p>功能说明：获取最大编码值/p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-08</p>
	 * <p>作者：李新宇</p>
	 */
	
	public ResultModle getMaxCode() throws Exception	
	{				
		Map<String, Object> params = SystemContext.getInParams();
		String code = (String) params.get("F_CODE");
		if(code==null||code.length()==0)
			code = "" ;
		Map<String, Object> resultBean=dao.getMaxCode(code);
		
		String maxCode=(String)resultBean.get("F_CODE");
		int codelen = maxCode.length() ;
		String strRight = "" ;
		String strLeft = "" ;
		if(codelen>9)
		{
			strLeft = maxCode.substring(0, codelen-9).toString();
			strRight = maxCode.substring(codelen-9,codelen).toString();
		}
		else
		{
			strRight = maxCode ;
		}
		int oldcode = Integer.valueOf(strRight).intValue();
		oldcode = oldcode + 1 ;
		String newCode = String.valueOf(oldcode).toString();
		int codelen2 = newCode.length();
		codelen = strRight.length();
		if(codelen2<codelen)
		{
			for(int i=0;i<(codelen-codelen2);i++)
			{
				newCode = "0"+newCode ;
			}			
		}
		newCode = strLeft + newCode ;
		resultBean.put("F_CODE", newCode);		
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);
	}
	
	/**
	 * 
	 * <p>函数名称：edit</p>
	 * <p>功能说明：编辑</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-08</p>
	 * <p>作者：李新宇</p>
	 * @throws Exception 
	 */
	public ResultModle edit() throws Exception{
		Map<String, Object> params = SystemContext.getInParams();
        String deptCode = (String) params.get("F_CODE");
        String deptID = (String) params.get("F_ID");
        @SuppressWarnings("unused")
		String deptCodeByID = dao.getCodeByID(deptID);
        String deptJC = this.getDWJC();
        Date currentTime = new Date();
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmsssss");
	    String dateString = formatter.format(currentTime);		
	    params.put("F_LASTTIME", dateString);  
	    params.put("F_ISLEAF", "0");
	    int level = dao.getLevel(deptCode);
	    params.put("F_LEVEL", String.valueOf(level).toString());
		boolean tag = false;
		String msg = "";
		String upDeptCode = dao.getUpBM(deptCode);
		String upDeptCodeByID = dao.getUpBM(deptCodeByID);
		String ChgCode = deptCode+" | "+upDeptCodeByID+" | "+upDeptCode ;
		String loadCode = "";
		String token =(String)params.get("Token");
		UserSession userSession = SystemContextUtil.getSessionMange().getUserSession((String)params.get("Token"));
		String loadUserType = userSession.getUserType().toString() ;
		int loadLevel = -1;
		if("A".equals(loadUserType)==false)
		{
			Object loadDeptCode = userSession.getAttribute("deptCode").toString() ;
			
			if(loadDeptCode!=null&&"".equals(loadDeptCode)==false)
			{
				loadCode = loadDeptCode.toString();
				loadLevel = dao.getLevel(loadCode);			
			}	
		}	
		
		try
		{   
			boolean isDeptCodeExist = dao.isBmExist(deptCode);  //判断新编码是否已存在
			boolean isCodeRight = this.isBmFix(deptCode);    //判断新编码是否符合规范要求
			boolean isDownDeptExist = false ;			     //判断是否当前修改单位存在下级
			if(deptCode.equals(deptCodeByID)==false)
			{
				isDownDeptExist=dao.isDownDEPTExist(deptCodeByID);
			}
			
			if(isCodeRight==true)  //判断编码 是否符合系统要求
			{
				if((level<=loadLevel)&&(deptCode.equals(loadCode)==false))
				{
					msg = "只能创建本级以下单位!" ;					
				}
				else
				{
					if((isDeptCodeExist==true)&&((deptCodeByID.equals(deptCode))==false)) //如果新编码已存在则不允许修改
					{
						msg = "编码已存在，请重新输入!" ;
						
					}else{
						
						if(isDownDeptExist==false)
						{
							if(deptCodeByID.equals(upDeptCode)==false&&(dao.isBmExist(upDeptCode)))
							{												
								if ("".equals(msg))
								{
																
								    msg = dao.edit(params);
								 	dao.changeUpleaf(ChgCode, "修改");								
									tag = true;
									msg = "修改成功!";
								}	
								
							}else{
								msg="上级编码不存在,请先添加上级编码!";
							}
								
						}else{
							msg = "存在下级单位,编码不能修改!" ;
						}
											
					}
				}
			}else{
				
				msg = "编码级长不符合预定规则:"+deptJC+"!"  ;
			}
		}
		catch(Exception e)
		{
			msg = "修改失败" + e;
		}
        
		Map<String, Object> resultBean=new HashMap<String, Object>();
		resultBean.put("msg", msg);
		resultBean.put("tag", tag);
		resultBean.put("F_CODE", deptCode);
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);

	}
	
	/**
	 * 
	 * <p>函数名称：del</p>
	 * <p>功能说明：删除，只删除最细级节点</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-08</p>
	 * <p>作者：陈金滨</p>
	 */
	public ResultModle del() throws Exception{
		Map<String, Object> params = SystemContext.getInParams(); 
	    String deptID = (String) params.get("F_ID");	
	    String deptCodeByID = dao.getCodeByID(deptID);
	    String upBm = dao.getUpBM(deptCodeByID);
		boolean tag=false;
		
		//判断是否是最细级，最细级才能删除，最细级节点返回true
		boolean isLeaf = dao.isLeaf(deptID);
		boolean isDeptUsed = dao.isDeptUsed(deptID); //单位是否被使用
		String msg =""; 
		try
		{   if(isLeaf)
		    {
			    if(isDeptUsed)
			    {
			    	msg = "该单位已被使用,不能删除!";
			    }
			    else
			    {
			    	msg = dao.del(params);		
			    	if(upBm!=null&&"".equals(upBm)==false)
			    	{
			    		dao.changeUpleaf(upBm, "删除");	
			    	}			    	
					if("".equals(msg))
					{
						tag = true;
						msg = "删除成功!";
					}
					else
					{
						msg = "删除失败!";
					}	
			    }			    
		    }
		    else
		    {
		    	msg="存在下级单位，不能删除!";
		    }	

		}
		catch(Exception e)
		{
			msg = "删除失败 " + e;
		}
		
		Map<String, Object> resultBean=new HashMap<String, Object>();
		resultBean.put("msg", msg);
		resultBean.put("tag", tag);
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);

	}
	
	/**
	 * 
	 * <p>函数名称：add</p>
	 * <p>功能说明：添加</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-08</p>
	 * <p>作者：陈金滨</p>
	 * @throws Exception 
	 */
	public ResultModle add() throws Exception{
		Map<String, Object> params = SystemContext.getInParams();
		boolean tag = false;
		String code = (String) params.get("F_CODE");
		String vDWJC =getDWJC();//取单位级长		
		String deptType = (String) params.get("F_TYPE");
		String msg = "";
		int leave,isleaf,lenJC,temp ;
		lenJC = vDWJC.length();
		temp = 0; leave = -1 ;
		//判断级数
		isleaf = 1 ;
		leave = dao.getLevel(code);
		
		String token =(String)params.get("Token");
		UserSession userSession = SystemContextUtil.getSessionMange().getUserSession((String)params.get("Token"));
		String loadUserType = userSession.getUserType().toString() ;
		int loadLevel = -1;
		if("A".equals(loadUserType)==false)
		{
			Object loadDeptCode = userSession.getAttribute("deptCode").toString() ;
			
			if(loadDeptCode!=null&&"".equals(loadDeptCode)==false)
			{
				String loadCode = loadDeptCode.toString();
				loadLevel = dao.getLevel(loadCode);			
			}	
		}	
		
		String upbm = dao.getUpBM(code) ;		
		boolean isUpbmFix = true ;
		if(upbm==null||"".equals(upbm))
		{
			msg = "" ;
			isUpbmFix = false ;
		}
		else
		{
			boolean IsUpbmExist = dao.isBmExist(upbm);
			if(IsUpbmExist)
			{				
				if(leave>1)
					isUpbmFix = false ;	
			}
		}		
	   Date currentTime = new Date();
	   SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmsssss");
	   String dateString = formatter.format(currentTime);
	   params.put("F_LEVEL", leave);
	   params.put("F_ISLEAF", isleaf);
	   params.put("F_LASTTIME", dateString);
	   params.put("F_STATE", "0");
		try
		{
			boolean isBmExist = dao.isBmExist(code);
			boolean isBmRight = this.isBmFix(code);
			if(leave==-1)
			{
				msg = "编码级长不符合预定规则:"+vDWJC+"!" ;
				
			}
			else
			{
				if(isBmRight==true)
				{					
					if(leave>loadLevel)
					{					
						if(isBmExist!=true)
						{								
							if(!isUpbmFix)
							{										
		                        if("".equals(msg))
		                        {
			   						msg = dao.add(params);									
									boolean isChange = dao.changeUpleaf(upbm,"新增");//更改上级最细级字段								
									tag = true;
									msg = "新增成功!";
									
		                        }else{msg="新增失败!";};			                        	
		                        
							}else{msg = "上级单位不存在,请先增加上级单位!" ;}	 
								
						}else{ msg ="已存在此编码，请重新输入!";}	
						
					}else{msg = "只能创建本级以下单位!" ;	}	
					
				}else{msg = "编码级长不符合预定规则:"+vDWJC+"!"  ;}
			}
		}
		catch(Exception e)
		{
			msg = "新增失败" + e;
		}
		Map<String, Object> resultBean=new HashMap<String, Object>();
		resultBean.put("msg", msg);
		resultBean.put("tag", tag);
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);

	}
	/**
	 * 
	 * <p>函数名称：editState</p>
	 * <p>功能说明：更改使用单位状态</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-28</p>
	 * <p>作者：陈金滨</p>
	 * @throws Exception 
	 */
	public ResultModle editState() throws Exception{
		Map<String, Object> params = SystemContext.getInParams();

		boolean tag = false;
		String msg = "";
        Date currentTime = new Date();
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmsssss");
	    String dateString = formatter.format(currentTime);		
	    params.put("F_LASTTIME", dateString);		
	    String isState = (String) params.get("F_STATE");
		try
		{   			
			if("".equals(msg)) 
			{				
				msg = dao.edit(params);
				tag = true;
				if("0".equals(isState))
				{
					msg = "启用成功!";	
				}
				else
				{
					msg = "停用成功!";
				}
						
			}		
		}
		catch(Exception e)
		{
			msg = "操作失败" + e;
		}
        
		Map<String, Object> resultBean=new HashMap<String, Object>();
		resultBean.put("msg", msg);
		resultBean.put("tag", tag);
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);

	}
	
	/**
	 * 
	 * <p>函数名称：getParentID</p>
	 * <p>功能说明：取父节点id</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-05-03</p>
	 * <p>作者：陈金滨</p>
	 */
	public ResultModle getParentID(String code) throws Exception
	{				
		Map<String, Object> params = SystemContext.getInParams();
		String child = (String) params.get("F_CODE");
		String parent = dao.getUpBM(child);
		Map<String, Object> childBean = dao.getInfoByCode(child);
		String childID = (String) childBean.get("F_ID");
		Map<String, Object> resultBean= new HashMap<String, Object>();
		resultBean=dao.getInfoByCode(parent);
		if(resultBean==null||"".equals(resultBean))
		{
			resultBean= new HashMap<String, Object>();
			resultBean.put("F_ID", "999");
		}
		resultBean.put("F_CHILD", childID);
		
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);
	}		
	/**
	 * 
	 * <p>函数名称：initDeptType</p>
	 * <p>功能说明：单位类型下拉列表</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-29</p>
	 * <p>作者：陈金滨</p>
	 */
	public ResultModle initDeptType() throws Exception
	{				
		List<Map> resultBean= new ArrayList();
		Map<String, Object> vMap1 = new HashMap<String, Object>();
		vMap1.put("id", "分类");
		vMap1.put("text", "分类");
		resultBean.add(vMap1);
		Map<String, Object> vMap4 = new HashMap<String, Object>();
		vMap4.put("id", "单位");
		vMap4.put("text", "单位");
		resultBean.add(vMap4);
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);
	}	
	/**
	 * 
	 * <p>函数名称：initDeptTypeForQry</p>
	 * <p>功能说明：单位类型下拉列表</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-29</p>
	 * <p>作者：陈金滨</p>
	 */	
	public ResultModle initDeptTypeForQry() throws Exception
	{				
		List<Map> resultBean= new ArrayList();
		Map<String, Object> vMap0 = new HashMap<String, Object>();
		vMap0.put("id", "");
		vMap0.put("text", "所有");
		resultBean.add(vMap0);
		Map<String, Object> vMap1 = new HashMap<String, Object>();
		vMap1.put("id", "分类");
		vMap1.put("text", "分类");
		resultBean.add(vMap1);
		Map<String, Object> vMap4 = new HashMap<String, Object>();
		vMap4.put("id", "单位");
		vMap4.put("text", "单位");
		resultBean.add(vMap4);
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);
	}		
	
	/**
	 * 
	 * <p>函数名称：getDWJC</p>
	 * <p>功能说明：取单位级长/p>
	 * <p>返回值：String类型级长</p>
	 * <p>创建时间：2012-03-08</p>
	 * <p>作者：陈金滨</p>
	 * @param MaxCode 
	 */
	public String getDWJC() throws Exception
	{				
		String result = "" ;
		Map<String, Object> resultBean=dao.getDWJC();
		result = (String) resultBean.get("F_ITEM1");

		return result;
	}	
	/**
	 * 
	 * <p>函数名称：getJC</p>
	 * <p>功能说明：单位级长/p>
	 * <p>返回值：Map类型级长</p>
	 * <p>创建时间：2012-03-08</p>
	 * <p>作者：陈金滨</p>
	 * @param MaxCode 
	 */
	public ResultModle getJC() throws Exception
	{				
		Map<String, Object> resultBean=dao.getDWJC();

		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);
	}

	
	/**
	 * 
	 * <p>函数名称：IsBmFix</p>
	 * <p>功能说明：判断编码是否符合级长规范</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-19</p>
	 * <p>作者：陈金滨</p>
	 * @param <Boolen>
	 * @param MaxCode 
	 */
	public boolean isBmFix(String code) throws Exception
	{				
		boolean result = false ;
		int js = dao.getLevel(code) ;//求编码级数，-1 为不符合级长要求
		if(js!=-1)
		{
			result = true ;	
		}		
		return result;
	}			
	/**
	 * 
	 * <p>函数名称：SetJC</p>
	 * <p>功能说明：设置级长</p>
	 * <p>参数说明：</p>
	 * <p>创建时间：2012-03-27</p>
	 * <p>作者：陈金滨</p>
	 * @throws Exception 
	 */
	public ResultModle setJC() throws Exception{
		Map<String, Object> params = SystemContext.getInParams();
		boolean tag = false;
		String msg = "" ; 
		
		//取系统设置表中单位级长
		Map<String, Object> vDWJC = dao.getDWJC();   
		String OLDJC = (String) vDWJC.get("F_ITEM1") ;
		if(OLDJC==null)
		{
			OLDJC="";
		}
		
		//取已使用的最大级长
		Map<String, Object> JS = dao.getMaxJS();      		
		Object temp =  JS.get("F_LEVEL");
		String OLDJS = "";
		int MaxJS = 0 ;
		if(temp!=null&&("".equals(temp)==false))
		{
			OLDJS = String.valueOf(temp).toString();		
			MaxJS = Integer.parseInt(OLDJS); 
		}		  
		
		//新级长级数
		String JC = (String) params.get("F_ITEM1");		
		int NewMaxJS = JC.length();     
		try
		{
	    // 1. 如果新旧级长相同，则提示更改成功
		// 2. 如果新旧编码不相同，则判断级数，如果新级长级数小于当前编码已使用的级数，则不能更改
		// 3. 如果级数等于已使用的级数，则判断新级长是否与原级长的前 n位（n位已使用级数）相同，相同则可以修改。
		// 4. 如果新级长级数大于当前编码已使用的级数，则判断 新级长前几位必须和旧级长相同
			if(JC.equals(vDWJC))
			{
				tag = true;
				msg = "更新级长成功!" ;
			}
			else
			{
				if(NewMaxJS<=MaxJS)
				{
					if(NewMaxJS<MaxJS)
					{
						msg ="当期编码已使用至第"+OLDJS+"级，请从第"+String.valueOf(MaxJS+1).toString()+"级开始更改!" ;
					}
					else
					{
						String oJC = OLDJC.substring(0,MaxJS);
						String nJC = JC.substring(0, MaxJS);
						if(oJC.equals(nJC))
						{
							if(dao.setJC(JC))
							{
								tag = true;
								msg = "修改级长成功!";
							}
							else
							{
								tag = false;
								msg = "修改级长失败!";
							}	
						}
						else
						{
							msg ="当期编码已使用至第"+OLDJS+"级，请从第"+String.valueOf(MaxJS+1).toString()+"级开始更改!" ;	
						}		
					}									
				}
				else
				{
					String oJC = OLDJC.substring(0,MaxJS);
					String nJC = JC.substring(0, MaxJS);
					if(oJC.equals(nJC))
					{
						if(dao.setJC(JC))
						{
							tag = true;
							msg = "修改级长成功!";
						}
						else
						{
							tag = false;
							msg = "修改级长失败!";
						}
					}
					else
					{
						msg = "当期编码已使用至第"+OLDJS+"级，请从第"+String.valueOf(MaxJS+1).toString()+"级开始更改!" ;
					}
				}
			}
			

		}
		catch(Exception e)
		{
			msg = "修改级长失败" + e;
		}
		Map<String, Object> resultBean=new HashMap<String, Object>();
		resultBean.put("msg", msg);
		resultBean.put("tag", tag);
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);

	}	
	
}
